<template>
	<!-- 头部搜索条件 -->
	<a-card :bordered="false" class="mb-3">
		<!-- <a-breadcrumb separator=">" class="mb-4 pl-[10px]">
			<a-breadcrumb-item>合同管理</a-breadcrumb-item>
			<a-breadcrumb-item><a href="">合同管理</a></a-breadcrumb-item>
		</a-breadcrumb> -->
		<div class="flex justify-between items-center">
			<a-space :size="16">
				<a-input-group compact>
					<a-select v-model:value="searchType" style="width: 150px" @change="searchText = ''">
						<a-select-option :value="0">合同编号</a-select-option>
						<a-select-option :value="1">甲方抬头</a-select-option>
						<a-select-option :value="2">甲方联系人/法人</a-select-option>
						<a-select-option :value="3">甲方联系电话</a-select-option>
					</a-select>
					<a-input
						v-model:value="searchTextComputed"
						style="width: 200px"
						placeholder="请输入关键字搜索"
						@pressEnter="table.clearRefreshSelected(true)"
					></a-input>
				</a-input-group>
				<a-input-group compact>
					<a-select
						placeholder="请选择"
						v-model:value="searchOption.userType"
						class="w-[100px]"
						:options="[
							{ label: '创建人', value: 0 },
							{ label: '签约人', value: 1 }
						]"
						:filter-option="false"
						@change="onUserTypeChange"
					></a-select>
					<a-select
						placeholder="请选择"
						v-model:value="searchOption.userVal"
						class="w-[200px]"
						:options="userList"
						:filter-option="false"
						allowClear
						showSearch
						labelInValue
						@search="searchCreater"
						@change="changeCreater"
					></a-select>
				</a-input-group>
				<a-button type="primary" @click="table.refresh(true)">查询</a-button>
				<a-button @click="screenVisible = true">更多筛选</a-button>
			</a-space>
			<a-space>
				<!--				<a-button v-if="hasPerm('bizContractSwitch') && erpStatus" type="primary" @click="onSwitchContract"-->
				<!--					>合同转换</a-button-->
				<!--				>-->
				<a-button v-if="hasPerm('bizContractAdd')" type="primary" @click="onAddContract">新增合同</a-button>
			</a-space>
		</div>
	</a-card>
	<!-- 表格展示区域 -->
	<!--	class="h-full"-->
	<a-card :bordered="false">
		<s-table
			ref="table"
			:columns="columns"
			:data="loadData"
			:page-num="pageNum"
			:size="pageSize"
			bordered
			:row-key="(record) => record.id"
			:tool-config="toolConfig"
			:scroll="{ x: 1200 }"
		>
			<template #bodyCell="{ column, record }">
				<template v-if="column.dataIndex === 'code'">
					<a v-if="hasPerm('bizContractView')" @click="onDetail(record.id)">{{ record.code }}</a>
					<span v-else>{{ record.code }}</span>
				</template>
				<template v-if="column.dataIndex === 'balancePayment'">
					<span>{{ record.paymentMethod === 'FULL' ? '-' : record.balancePayment ?? '-' }}</span>
				</template>
				<template v-if="column.dataIndex === 'depositAmount'">
					<span>{{ record.paymentMethod === 'FULL' ? '-' : record.depositAmount ?? '-' }}</span>
				</template>
				<template v-if="column.dataIndex === 'contractStatus'">
					<span>{{ statusEnum[record.contractStatus] }}</span>
				</template>
				<template v-if="column.dataIndex === 'signPayment'">
					<span>{{ signPayEnum[record.signPayment] }}</span>
				</template>
				<template v-if="column.dataIndex === 'paymentMethod'">
					<span>{{ payMethodEnum[record.paymentMethod] }}</span>
				</template>
				<template v-if="column.dataIndex === 'approvalStatus'">
					<span>{{ approvalStatusEnum[record.approvalStatus] }}</span>
				</template>
				<template v-if="column.dataIndex === 'financeApprovalStatus'">
					<span>{{ approvalStatusEnum[record.financeApprovalStatus] }}</span>
				</template>
				<template v-if="column.dataIndex === 'action'">
					<a-popover placement="left">
						<template #content>
							<div class="flex flex-col">
								<a-button v-if="hasPerm('bizContractView')" type="link" @click="onDetail(record.id)">
									查看详情
								</a-button>
								<template v-if="record.operateAction === 'add'">
									<!-- 电子合同 -->
									<template v-if="record.signMethod === '0'">
										<a-button
											v-if="hasPerm('bizContractSendUp') && record.contractStatus === 'ToContractStart'"
											type="link"
											@click="sendUpContract(record.id)"
											>发起合同</a-button
										>
										<a-button
											v-if="
												hasPerm('bizContractSendUpAgain') &&
												(['Withdraw', 'ApprovalRejection', 'ToSigned'].includes(record.contractStatus) ||
													(record.contractType === 'TRANS' && record.contractStatus === 'FinanceRejection'))
											"
											type="link"
											@click="sendUpAgainContract(record.id)"
											>重新发起</a-button
										>
										<a-button
											type="link"
											v-if="hasPerm('bizContractRevoke') && record.contractStatus === 'PendingApproval'"
											@click="revoke(record.id)"
											>合同撤回</a-button
										>
										<a-button v-if="hasPerm('bizContractDownload')" type="link" @click="downloadContract(record.id)"
											>合同下载</a-button
										>
										<a-button
											v-if="
												hasPerm('bizContractUploadVoucher') &&
												record.signPayment === 'OnlineSignedUnpaid' &&
												record.contractStatus === 'VoucherUpload'
											"
											type="link"
											@click="toUploadVoucher(record.id)"
											>上传凭证</a-button
										>
										<a-button
											type="link"
											v-if="
												hasPerm('bizContractViewVoucher') &&
												record.signPayment === 'OnlineSignedUnpaid' &&
												record.voucherImg
											"
											@click="checkVoucher(record)"
											>查看凭证</a-button
										>
										<a-button
											type="link"
											v-if="
												hasPerm('bizContractUploadContractVoucher') &&
												record.signPayment === 'OfflineSignedPaid' &&
												(record.contractStatus === 'ToSigned' || record.contractStatus === 'ContractVoucherUpload')
											"
											@click="toUpContract(record.id)"
											>上传合同及凭证</a-button
										>
										<a-button
											type="link"
											v-if="
												hasPerm('bizContractViewContractVoucher') &&
												record.signPayment === 'OfflineSignedPaid' &&
												record.voucherImg &&
												record.contractImg
											"
											@click="checkContract(record)"
											>查看合同及凭证</a-button
										>
										<a-button
											type="link"
											v-if="hasPerm('bizContractApproveFinance') && record.contractStatus === 'FinanceApproval'"
											@click="approve(record)"
											>财务审批</a-button
										>
										<a-button v-if="hasPerm('bizContractPreview')" type="link" @click="contractPreview(record.id)"
											>合同预览</a-button
										>
										<a-button
											v-if="
												hasPerm('bizContractPay') &&
												record.signPayment === 'OnlineSignedPaid' &&
												record.contractStatus === 'CustomerPay'
											"
											type="link"
											@click="onPay(record)"
										>
											重新支付
										</a-button>
										<a-button
											v-if="
												hasPerm('bizContractPayChange') &&
												record.signPayment === 'OnlineSignedPaid' &&
												record.contractStatus === 'CustomerPay'
											"
											type="link"
											@click="onPayChange(record)"
										>
											支付变更
										</a-button>
									</template>
								</template>
								<!-- 纸质合同 -->
								<template v-if="record.signMethod === '1'">
									<a-button
										type="link"
										v-if="
											hasPerm('bizContractSendUpAgain') &&
											['ApprovalRejection', 'FinanceRejection'].includes(record.contractStatus)
										"
										@click="sendUpAgainContract(record.id)"
										>重新发起</a-button
									>
									<a-button
										type="link"
										v-if="hasPerm('bizContractRevoke') && record.contractStatus === 'PendingApproval'"
										@click="revoke(record.id)"
										>合同撤回</a-button
									>
									<a-button
										type="link"
										v-if="hasPerm('bizContractApproveBusiness') && record.contractStatus === 'PendingApproval'"
										@click="approveBusiness(record)"
										>业务审批</a-button
									>
									<a-button
										type="link"
										v-if="hasPerm('bizContractApproveFinance') && record.contractStatus === 'FinanceApproval'"
										@click="approve(record)"
										>财务审批</a-button
									>
								</template>
								<a-button
									v-if="hasPerm('bizContractDelete') && record.contractStatus !== 'tradeOver'"
									type="link"
									@click="onDelete(record)"
								>
									合同删除
								</a-button>
								<a-button
									v-if="hasPerm('bizContractCancel') && record.contractStatus === 'tradeOver'"
									type="link"
									@click="onCancel(record)"
								>
									合同作废
								</a-button>
								<a-button
									v-if="isTenantOderControls === 0 || isTenantOderControls === 2"
									type="link"
									@click="toScheduling(record, '1')"
								>
									报单信息表
								</a-button>
								<a-button
									v-if="isTenantOderControls === 0 || isTenantOderControls === 1"
									type="link"
									@click="toScheduling(record, '2')"
								>
									派单信息表
								</a-button>
							</div>
						</template>
						<a>操作</a>
					</a-popover>
				</template>
			</template>
		</s-table>
	</a-card>
	<!-- 更多筛选条件 -->
	<a-modal
		v-model:visible="screenVisible"
		title="更多筛选"
		:footer="null"
		:closable="false"
		:width="500"
		@cancel="cancelMoreSearch"
	>
		<a-form :label-col="labelCol">
			<a-form-item label="合同状态">
				<a-select
					v-model:value="moreSearch.contractStatus"
					:options="businessApproveOptions"
					mode="multiple"
					max-tag-count="responsive"
					allowClear
					placeholder="请选择"
				></a-select>
			</a-form-item>
			<a-form-item label="签约方式">
				<a-select
					v-model:value="moreSearch.signMethod"
					:options="signMethodOptions"
					allowClear
					placeholder="请选择"
				></a-select>
			</a-form-item>
			<a-form-item label="签约场景">
				<a-select
					v-model:value="moreSearch.signPayment"
					:options="signPayOptions"
					allowClear
					placeholder="请选择"
				></a-select>
			</a-form-item>
			<a-form-item label="合同类型">
				<a-select
					v-model:value="moreSearch.contractType"
					:options="contractTypeOptions"
					allowClear
					placeholder="请选择"
				></a-select>
			</a-form-item>
			<a-form-item label="付款类型">
				<a-select
					v-model:value="moreSearch.paymentMethod"
					:options="payMethodOptions"
					allowClear
					placeholder="请选择"
				></a-select>
			</a-form-item>
			<a-form-item label="合同金额">
				<a-input-group compact>
					<a-select style="width: 30%" v-model:value="moreSearch.comparisonOperators" placeholder="请选择">
						<a-select-option value="gt">></a-select-option>
						<a-select-option value="eq">=</a-select-option>
						<a-select-option value="lt">&lt;</a-select-option>
					</a-select>
					<a-input-number style="width: 70%" v-model:value="moreSearch.contractAmount" placeholder="请输入" />
				</a-input-group>
			</a-form-item>
			<a-form-item label="服务类目">
				<a-cascader
					v-model:value="moreSearch.serviceCategoryId"
					:options="categorySearchs"
					changeOnSelect
					allowClear
					placeholder="请选择"
				></a-cascader>
			</a-form-item>
			<a-form-item label="签约日期">
				<a-range-picker
					class="w-full"
					valueFormat="YYYY-MM-DD"
					v-model:value="moreSearch.signingDate"
					:placeholder="['请选择', '请选择']"
				/>
			</a-form-item>
			<a-form-item label="合同模板">
				<a-select
					v-model:value="moreSearch.templateId"
					:options="templateOptions"
					allowClear
					placeholder="请选择"
				></a-select>
			</a-form-item>
			<a-form-item label="业务审批状态">
				<a-select
					v-model:value="moreSearch.approvalStatus"
					:options="approveStatusOptions"
					allowClear
					placeholder="请选择"
				></a-select>
			</a-form-item>
			<a-form-item label="财务审批状态">
				<a-select
					v-model:value="moreSearch.financeApprovalStatus"
					:options="approveStatusOptions"
					allowClear
					placeholder="请选择"
				></a-select>
			</a-form-item>
			<a-form-item label="乙方抬头">
				<a-select
					v-model:value="moreSearch.secondPartyId"
					:options="partyOptions"
					allowClear
					placeholder="请选择"
				></a-select>
			</a-form-item>
		</a-form>
		<div class="flex justify-between items-center mt-[40px]">
			<a-button type="link" @click="clearSearch">清空筛选</a-button>
			<a-space>
				<a-button type="primary" @click="doMoreSearch">筛选</a-button>
				<a-button @click="cancelMoreSearch">取消</a-button>
			</a-space>
		</div>
	</a-modal>
	<!-- 上传凭证 -->
	<a-modal
		v-model:visible="voucherVisibel"
		title="上传凭证"
		:width="500"
		@cancel="voucherShow.length = 0"
		@ok="confirmUpload"
		:confirmLoading="uploadLoading"
	>
		<a-row :gutter="16" class="p-6">
			<a-col class="leading-8">付款凭证</a-col>
			<a-col>
				<a-upload
					v-model:file-list="voucherShow"
					name="file"
					:multiple="true"
					:before-upload="contractOrVoucherBeforeUpload"
					accept="image/*,.pdf"
				>
					<a-button type="primary">点击上传</a-button>
				</a-upload>
				<div class="mt-1 text-gray-500">只能上传图片或pdf文件，且不超过10MB</div>
			</a-col>
		</a-row>
	</a-modal>
	<!-- 上传合同及凭证 -->
	<a-modal
		v-model:visible="contractUpVisibel"
		title="上传合同及凭证"
		:width="500"
		@cancel="contractCancel"
		@ok="confirmContractUpload"
		:confirmLoading="uploadLoading"
	>
		<a-row :gutter="16" class="p-6">
			<a-col class="leading-8">合同照片</a-col>
			<a-col>
				<a-upload
					v-model:file-list="contractShow"
					name="file"
					:multiple="true"
					:before-upload="contractOrVoucherBeforeUpload"
					accept="image/*,.pdf"
				>
					<a-button type="primary">点击上传</a-button>
				</a-upload>
				<div class="mt-1 text-gray-500">只能上传图片或pdf文件，且不超过10MB</div>
			</a-col>
		</a-row>
		<a-row :gutter="16" class="p-6">
			<a-col class="leading-8">付款凭证</a-col>
			<a-col>
				<a-upload
					v-model:file-list="voucherShow"
					name="file"
					:multiple="true"
					:before-upload="contractOrVoucherBeforeUpload"
					accept="image/*,.pdf"
				>
					<a-button type="primary">点击上传</a-button>
				</a-upload>
				<div class="mt-1 text-gray-500">只能上传图片或pdf文件，且不超过10MB</div>
			</a-col>
		</a-row>
	</a-modal>
	<!-- 查看合同及凭证/凭证 -->
	<a-drawer
		:title="checkType === 'contract' ? '查看合同及凭证' : '查看凭证'"
		placement="right"
		:closable="false"
		v-model:visible="imgCheckShow"
	>
		<div>
			<div>凭证查看（点击查看）</div>
			<div v-for="item in voucherSrc.split(',')" :key="item" class="mt-1">
				<img
					v-if="item.substr(item.lastIndexOf('.') + 1, item.length).toLowerCase() === 'pdf'"
					:width="100"
					src="/src/assets/images/pdf.png"
					class="object-contain cursor-pointer"
					@click="onPdfPreview(item)"
				/>
				<a-image v-else :width="300" :src="item" />
			</div>
		</div>
		<div v-if="checkType === 'contract'" class="mt-4">
			<div>合同查看（点击查看）</div>
			<div v-for="item in contractSrc.split(',')" :key="item" class="mt-1">
				<img
					v-if="item.substr(item.lastIndexOf('.') + 1, item.length).toLowerCase() === 'pdf'"
					:width="100"
					src="/src/assets/images/pdf.png"
					class="object-contain cursor-pointer"
					@click="onPdfPreview(item)"
				/>
				<a-image v-else :width="300" :src="item" />
			</div>
		</div>
	</a-drawer>
	<!-- 业务审批 -->
	<approve-business-modal
		v-if="approveBusinessVisible"
		v-model:visible="approveBusinessVisible"
		:info="businessInfo"
		@finished="table.refresh(true)"
	/>
	<!-- 财务审批 -->
	<approve-modal v-if="approveVisible" v-model:visible="approveVisible" :info="info" @finished="table.refresh(true)" />
	<!-- 新增合同 -->
	<add-contract-modal v-model:visible="addContractVisible" :info="contractInfo" @finished="table.refresh(true)" />
	<!-- 重新支付 -->
	<pay-modal ref="payModalRef" @finished="onPayFinish" />

	<!-- 支付变更 -->
	<pay-change-modal ref="payChangeModalRef" @finished="onPayChangeFinish" />

	<!-- 报单、派单 -->
	<el-dialog
		class="pay-img-dialog"
		:title="schedulingType === '1' ? '报单绩效信息' : '客户派单信息表'"
		v-model="bindVisibleScheduling"
		:show-close="true"
		:close-on-click-modal="false"
		width="1200px"
		top="10vh"
		custom-class="dispatch-dialog"
		@close="bindVisibleScheduling = false"
	>
		<customs-declaration
			v-if="bindVisibleScheduling && schedulingType === '1'"
			:contractInfo="selectedRow"
			@finished="onOrderFinish"
		/>
		<customer-scheduling
			v-if="bindVisibleScheduling && schedulingType === '2'"
			:contractInfo="selectedRow"
			@finished="onOrderFinish"
		/>
	</el-dialog>
</template>
<script setup>
	import { Modal, Upload } from 'ant-design-vue'
	import ApproveBusinessModal from './approveBusinessModal.vue'
	import ApproveModal from './approveModal.vue'
	import AddContractModal from './addContractModal.vue'
	import PayModal from './payModal.vue'
	import PayChangeModal from './payChangeModal.vue'
	import contractApi from '@/api/biz/bizContractApi'
	import erpApi from '@/api/biz/bizCommonApi'
	import uploadApi from '@/api/dev/fileApi'
	import tool from '@/utils/tool'
	import { message } from 'ant-design-vue'
	import {
		signPayEnum,
		payMethodEnum,
		statusEnum,
		approvalStatusEnum,
		signMethodOptions,
		signMethodEnum,
		contractTypeEnum,
		contractTypeOptions
	} from './enum/contractEnum'
	import { createVNode } from 'vue'
	import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
	import { useRouter } from 'vue-router'
	import useTableCache from '@/hook/useTableCache'
	import customerScheduling from '@/views/biz/contractManagement/customerScheduling.vue'
	import customsDeclaration from '@/views/biz/contractManagement/customsDeclaration.vue'
	import customerQwOrderApi from '@/api/biz/customerQwOrderApi'

	const router = useRouter()
	const tableCache = useTableCache('contractManagement', ['contractManagement', 'contractDetail'])

	const erpStatus = ref(false)
	const getLoginData = () => {
		const {
			account = '',
			password = '',
			tenantId = '',
			publicToken = '',
			erpStatus = '',
			crmStatus = ''
		} = tool.data.get('loginData') || {}
		return {
			account,
			password,
			tenantId,
			publicToken,
			erpStatus,
			crmStatus
		}
	}
	erpStatus.value = getLoginData().erpStatus === '1'

	/**
	 * ====================
	 *       基本逻辑
	 * ====================
	 */
	onBeforeMount(() => {
		const tableCacheData = tableCache.get()
		if (tableCacheData) {
			searchType.value = tableCacheData.searchType
			searchText.value = tableCacheData.searchText
			searchOption.value = tableCacheData.searchOption
			moreSearch.value = tableCacheData.moreSearch
			pageNum.value = tableCacheData.pageNum
			pageSize.value = tableCacheData.pageSize
		}

		getContractPartbList()
		getCategorys()
		getTemplates()
		getCreaters()

		// 获取提单配置
		customerQwOrderApi
			.getTenantOderControls({
				tenantId: tool.data.get('loginData').tenantId
			})
			.then((res) => {
				if (res) {
					isTenantOderControls.value = res.type
				}
			})
	})
	const addContractVisible = ref(false)
	const columns = [
		{
			title: '合同编号',
			dataIndex: 'code',
			width: 200,
			align: 'center',
			fixed: 'left'
		},
		{
			title: '合同模板',
			dataIndex: 'templateName',
			width: 200,
			align: 'center',
			ellipsis: true,
			customRender: ({ text }) => text || '-'
		},
		{
			title: '甲方抬头',
			dataIndex: 'firstParty',
			width: 260,
			align: 'center',
			ellipsis: true
		},
		{
			title: '乙方抬头',
			dataIndex: 'secondPartyName',
			width: 260,
			align: 'center',
			ellipsis: true
		},
		{
			title: '合同状态',
			dataIndex: 'contractStatus',
			align: 'center',
			width: 120
		},
		{
			title: '签约方式',
			dataIndex: 'signMethod',
			width: 100,
			align: 'center',
			customRender: ({ text }) => signMethodEnum[text] || '-'
		},
		{
			title: '签约场景',
			dataIndex: 'signPayment',
			width: 150,
			align: 'center'
		},
		{
			title: '合同类型',
			dataIndex: 'contractType',
			width: 150,
			align: 'center',
			customRender: ({ text }) => contractTypeEnum[text] || '-'
		},
		{
			title: '付款类型',
			dataIndex: 'paymentMethod',
			width: 100,
			align: 'center'
		},
		{
			title: '合同总金额',
			dataIndex: 'contractAmount',
			width: 120,
			align: 'center'
		},
		{
			title: '定金总金额',
			dataIndex: 'depositAmount',
			width: 120,
			align: 'center'
		},
		{
			title: '尾款总金额',
			dataIndex: 'balancePayment',
			width: 120,
			align: 'center'
		},
		{
			title: '尾款结清日期',
			dataIndex: 'balancePaymentTime',
			width: 150,
			align: 'center'
		},
		{
			title: '合同备注',
			dataIndex: 'remark',
			width: 200,
			align: 'center',
			ellipsis: true
		},
		{
			title: '签约人',
			dataIndex: 'secondPartyPerson',
			width: 120,
			align: 'center',
			ellipsis: true
		},
		{
			title: '创建人',
			dataIndex: 'createUserName',
			width: 120,
			align: 'center',
			ellipsis: true
		},
		{
			title: '创建时间',
			dataIndex: 'createAt',
			width: 150,
			align: 'center'
		},
		{
			title: '签约日期',
			dataIndex: 'signingDate',
			width: 150,
			align: 'center'
		},
		{
			title: '业务审批状态',
			dataIndex: 'approvalStatus',
			width: 120,
			align: 'center'
		},
		{
			title: '业务审批时间',
			dataIndex: 'approvalTime',
			width: 150,
			align: 'center'
		},
		{
			title: '财务审批状态',
			dataIndex: 'financeApprovalStatus',
			width: 120,
			align: 'center'
		},
		{
			title: '财务审批时间',
			dataIndex: 'financeApprovalTime',
			width: 150,
			align: 'center'
		},
		{
			title: '驳回原因',
			dataIndex: 'reason',
			width: 150,
			align: 'center',
			ellipsis: true,
			customRender: ({ record }) => record.rejectReason || record.approvalRejectReason || '-'
		}
	]
	columns.push({
		title: '操作',
		dataIndex: 'action',
		align: 'center',
		fixed: 'right',
		width: '100px'
	})
	/**
	 * 获取所有服务类目
	 */
	const categorySearchs = ref([])
	const getCategorys = () => {
		erpApi.getCategory().then((res) => {
			categorySearchs.value = res
		})
	}
	/**
	 * 合同模板
	 */
	const templateOptions = ref([])
	const getTemplates = () => {
		contractApi.getBusinessTemplateList({}).then((res) => {
			templateOptions.value = res.map((item) => {
				return {
					label: item.templateName,
					value: item.templateId
				}
			})
		})
	}

	const searchType = ref(0)
	const searchText = ref('')
	const searchTextComputed = computed({
		get() {
			return searchText.value
		},
		set(val) {
			searchText.value = val.replace(/(^\s*)|(\s*$)/g, '')
		}
	})
	const searchOption = ref({
		code: undefined,
		firstParty: undefined,
		firstPartyPerson: undefined,
		firstPartyMobile: undefined,
		userType: 0,
		userVal: undefined,
		createUser: undefined,
		secondPartyPerson: undefined
	})
	/**
	 * 获取业务员搜索
	 */
	const userList = ref([])
	const searchKey = ref('')
	const saveUserList = ref([])
	const onUserTypeChange = () => {
		searchOption.value.userVal = ''
		getCreaters()
	}
	const getCreaters = () => {
		const requestData = !searchOption.value.userType
			? contractApi.authUserSelector({
					searchKey: searchKey.value
			  })
			: contractApi.signUserList({
					type: 0 // 空或0-合同列表 1-历史合同列表 2-订单合同
			  })
		requestData.then((res) => {
			userList.value = res.map((item) => {
				return !searchOption.value.userType
					? {
							label: item.name,
							value: item.id
					  }
					: {
							label: item,
							value: item
					  }
			})
			saveUserList.value = JSON.parse(JSON.stringify(userList.value))
		})
	}
	let timeout
	const searchCreater = (value) => {
		if (timeout) {
			clearTimeout(timeout)
			timeout = null
		}
		userList.value = saveUserList.value.filter((v) => {
			return v.label.indexOf(value) !== -1
		})
	}
	const changeCreater = (value) => {
		if (!value) {
			userList.value = JSON.parse(JSON.stringify(saveUserList.value))
		}
	}
	/**
	 * 乙方信息列表获取
	 */
	const partyOptions = ref([])
	const getContractPartbList = () => {
		contractApi.getContractPartbList().then((res) => {
			partyOptions.value = res.map((item) => {
				return {
					value: item.id,
					label: item.partyName
				}
			})
		})
	}
	// 签约场景
	const signPayOptions = tool.dictList('SignPayment')
	// 收款方式
	const payMethodOptions = tool.dictList('PAYMENT_METHOD')
	// 财务审批状态
	const approveStatusOptions = tool.dictList('FinanceApprovalStatus')
	// 合同状态
	const businessApproveOptions = tool.dictList('APPROVAL_STATUS')
	/**
	 * 更多筛选条件逻辑
	 */
	const screenVisible = ref(false)
	const labelCol = { style: { width: '100px' } }
	// 更多筛选条件初始值
	const moreDefaultSearch = {
		contractStatus: [],
		comparisonOperators: null,
		contractAmount: null,
		signMethod: null,
		signPayment: null,
		contractType: null,
		paymentMethod: null,
		signingDate: null,
		financeApprovalStatus: null,
		secondPartyId: null,
		serviceCategoryId: null,
		templateId: null,
		approvalStatus: null
	}
	const moreSearch = ref({ ...moreDefaultSearch })
	const clearSearch = () => {
		moreSearch.value = { ...moreDefaultSearch }
	}
	const doMoreSearch = () => {
		screenVisible.value = false
		table.value.refresh(true)
	}
	const cancelMoreSearch = () => {
		screenVisible.value = false
	}
	const toolConfig = { refresh: true, height: true, columnSetting: true, striped: false }
	const table = ref(null)
	const pageNum = ref(1)
	const pageSize = ref(10)

	/**
	 * 获取合同列表数据
	 */
	const loadData = (parameter) => {
		if (searchType.value === 0) {
			searchOption.value.code = searchText.value
			searchOption.value.firstParty = null
			searchOption.value.firstPartyPerson = null
			searchOption.value.firstPartyMobile = null
		} else if (searchType.value === 1) {
			searchOption.value.code = null
			searchOption.value.firstParty = searchText.value
			searchOption.value.firstPartyPerson = null
			searchOption.value.firstPartyMobile = null
		} else if (searchType.value === 2) {
			searchOption.value.code = null
			searchOption.value.firstParty = null
			searchOption.value.firstPartyPerson = searchText.value
			searchOption.value.firstPartyMobile = null
		} else if (searchType.value === 3) {
			searchOption.value.code = null
			searchOption.value.firstParty = null
			searchOption.value.firstPartyPerson = null
			searchOption.value.firstPartyMobile = searchText.value
		}

		const { userType, userVal } = searchOption.value
		if (userVal) {
			if (userType === 0) {
				searchOption.value.createUser = userVal.value
				searchOption.value.secondPartyPerson = null
			} else if (userType === 1) {
				searchOption.value.createUser = null
				searchOption.value.secondPartyPerson = userVal.label
			}
		} else {
			searchOption.value.createUser = null
			searchOption.value.secondPartyPerson = null
		}
		const { userVal: userData, ...otherOption } = searchOption.value

		const params = {
			...otherOption,
			...moreSearch.value,
			...parameter,
			type: '0'
		}

		params.contractStatus =
			params.contractStatus && params.contractStatus.length ? moreSearch.value.contractStatus.join(',') : null

		if (params.serviceCategoryId) {
			const [serviceClassId = null, serviceTypeId = null, serviceProjectId = null] = params.serviceCategoryId
			params.serviceCategoryId = params.serviceCategoryId.join(',')
			params.serviceClassId = serviceClassId
			params.serviceTypeId = serviceTypeId
			params.serviceProjectId = serviceProjectId
		}
		if (params.signingDate) {
			params.startSigningDate = params.signingDate[0]
			params.endSigningDate = params.signingDate[1]
			delete params.signingDate
		}
		return contractApi.getContractList(params).then((res) => {
			return res
		})
	}

	/**
	 * 轮询状态
	 */
	const timer = ref(null)
	const timeLong = ref(4 * 60 * 1000)
	const clearCircleStatus = () => {
		clearInterval(timer.value)
		timer.value = null
		timeLong.value = 4 * 60 * 1000
	}
	const startCircleStatus = () => {
		table.value.refresh()
		clearCircleStatus()
		timer.value = setInterval(() => {
			if (timeLong.value > 0) {
				timeLong.value -= 30000
				table.value.refresh()
			} else {
				clearCircleStatus()
			}
		}, 30000)
	}

	onBeforeUnmount(() => {
		clearCircleStatus()
	})

	/**
	 * ====================
	 *       列表操作
	 * ====================
	 */
	/**
	 * 合同转换
	 */
	// const onSwitchContract = () => {}

	/**
	 * 新增合同
	 */
	const onAddContract = () => {
		contractInfo.value = null
		addContractVisible.value = true
	}

	/**
	 * 详情
	 */
	const onDetail = (id) => {
		tool.limitClick(() => {
			const { localPagination } = table.value
			tableCache.set({
				searchType: searchType.value,
				searchText: searchText.value,
				searchOption: searchOption.value,
				moreSearch: moreSearch.value,
				pageNum: localPagination.current,
				pageSize: localPagination.pageSize
			})
			router.push(`/biz/contractManagement/contractDetail/${id}`)
		})
	}

	/**
	 * 发起合同
	 */
	const sendUpContract = (id) => {
		Modal.confirm({
			title: '提示',
			content: '此操作将发起合同，是否继续？',
			okText: '确认',
			onOk: () => {
				contractApi.sendUpContract({ id }).then(() => {
					message.success('合同发起成功')

					startCircleStatus()
				})
			},
			closable: true,
			cancelText: '取消'
		})
	}

	/**
	 * 重新发起
	 */
	const contractInfo = ref(null)
	const sendUpAgainContract = (id) => {
		contractApi.getContractDetail({ id }).then((res) => {
			contractInfo.value = res
			addContractVisible.value = true
		})
	}

	/**
	 * 合同撤回
	 */
	const revoke = (id) => {
		Modal.confirm({
			title: '提示',
			content: '此操作将撤回该条信息，是否继续？',
			okText: '确认',
			onOk: () => {
				contractApi.recallContract({ id }).then(() => {
					message.success('撤回成功')
					table.value.refresh(true)
				})
			},
			closable: true,
			cancelText: '取消'
		})
	}
	/**
	 * 下载合同
	 */
	const downloadContract = (id) => {
		contractApi.downContract({ id }).then((res) => {
			// downloadUtil.resultDownload(res)
			const a = document.createElement('a')
			fetch(res)
				.then((resp) => resp.blob())
				.then((blob) => {
					// 将链接地址字符内容转变成blob地址
					a.href = URL.createObjectURL(blob)
					// @ts-ignore
					a.download = '合同下载-' + new Date().getTime() + '.pdf' // 下载文件的名字
					// a.download = url.split('/')[url.split('/').length -1] //  // 下载文件的名字
					document.body.appendChild(a)
					a.click()
					document.body.removeChild(a)
				})
		})
	}

	/**
	 * 合同及凭证上传限制
	 */
	const beforeUpload = (file) => {
		const isJpgOrPng =
			file.type === 'image/jpg' ||
			file.type === 'image/jpeg' ||
			file.type === 'image/png' ||
			file.type === 'application/pdf'
		if (!isJpgOrPng) {
			message.error('只能上传JPG/PNG/PDF格式的图片!')
		}
		const isLt10M = file.size / 1024 / 1024 < 10
		if (!isLt10M) {
			message.error('图片大小必须小于10MB!')
		}
		return (isJpgOrPng && isLt10M) || Upload.LIST_IGNORE
	}
	const contractOrVoucherBeforeUpload = (file) => {
		const result = beforeUpload(file)
		if (result && result !== Upload.LIST_IGNORE) {
			return false
		}
		return result
	}

	/**
	 * 上传凭证
	 */
	const voucherVisibel = ref(false)
	const voucherShow = ref([])
	const voucherReq = ref({
		id: undefined,
		voucherImg: undefined
	})
	const toUploadVoucher = (id) => {
		voucherShow.value = []
		voucherReq.value = {
			id,
			voucherImg: undefined
		}
		voucherVisibel.value = true
	}

	/**
	 * 确定上传凭证
	 */
	const uploadLoading = ref(false)
	const confirmUpload = () => {
		if (voucherShow.value.length === 0) {
			message.warning('请上传图片')
			return
		}
		const fileDataList = new FormData()
		voucherShow.value.forEach((item) => {
			fileDataList.append('files', item.originFileObj)
		})
		uploadLoading.value = true
		uploadApi.fileUploadAliyunReturnListUrl(fileDataList).then((res) => {
			voucherReq.value.voucherImg = res
			contractApi
				.uploadVoucher(voucherReq.value)
				.then(() => {
					voucherVisibel.value = false
					table.value.refresh(true)
					uploadLoading.value = false
				})
				.finally(() => {
					uploadLoading.value = false
				})
		})
	}
	/**
	 * 上传合同及凭证
	 */
	const contractUpVisibel = ref(false)
	const contractShow = ref([])
	const upContractReq = ref({
		id: undefined,
		voucherImg: undefined,
		contractImg: undefined
	})
	const toUpContract = (id) => {
		contractCancel()
		upContractReq.value = {
			id,
			voucherImg: undefined,
			contractImg: undefined
		}
		contractUpVisibel.value = true
	}

	const contractCancel = () => {
		contractShow.value = []
		voucherShow.value = []
	}
	/**
	 * 确定上传合同及凭证
	 */
	const confirmContractUpload = () => {
		if (voucherShow.value.length === 0 || contractShow.value.length === 0) {
			message.warning('请上传图片')
			return
		}

		const fileDataList = new FormData()
		voucherShow.value.forEach((item) => {
			fileDataList.append('files', item.originFileObj)
		})
		const fileContractList = new FormData()
		contractShow.value.forEach((item) => {
			fileContractList.append('files', item.originFileObj)
		})
		uploadLoading.value = true
		Promise.all([
			uploadApi.fileUploadAliyunReturnListUrl(fileDataList),
			uploadApi.fileUploadAliyunReturnListUrl(fileContractList)
		])
			.then((res) => {
				upContractReq.value.voucherImg = res[0]
				upContractReq.value.contractImg = res[1]
				contractApi.uploadContractVoucher(upContractReq.value).then(() => {
					contractUpVisibel.value = false
					uploadLoading.value = false
					table.value.refresh(true)
				})
			})
			.finally(() => {
				uploadLoading.value = false
			})
	}
	/**
	 * 合同凭证查看
	 */
	const imgCheckShow = ref(false)
	const checkType = ref(null)
	// 查看凭证
	const voucherSrc = ref('')
	const checkVoucher = (record) => {
		checkType.value = 'voucher'
		voucherSrc.value = record.voucherImg
		imgCheckShow.value = true
	}
	// 查看合同凭证
	const contractSrc = ref('')
	const checkContract = (record) => {
		checkType.value = 'contract'
		voucherSrc.value = record.voucherImg
		contractSrc.value = record.contractImg
		imgCheckShow.value = true
	}
	const onPdfPreview = (url) => {
		window.open(url.replace('http://', 'https://'))
	}
	/**
	 * 业务审批
	 */
	const approveBusinessVisible = ref(false)
	const businessInfo = ref({})
	const approveBusiness = (row) => {
		contractApi.getContractDetail({ id: row.id }).then((res) => {
			businessInfo.value = { ...row, ...res }
			approveBusinessVisible.value = true
		})
	}
	/**
	 * 财务审批
	 */
	const approveVisible = ref(false)
	const info = ref({})
	const approve = (row) => {
		contractApi.getContractDetail({ id: row.id }).then((res) => {
			info.value = { ...row, ...res }
			approveVisible.value = true
		})
	}
	/**
	 * 合同预览
	 */
	const contractPreview = (id) => {
		contractApi.downContract({ id }).then((res) => {
			window.open(res)
		})
	}

	/**
	 * 重新支付
	 */
	const payModalRef = ref(null)
	const onPay = ({ code }) => {
		payModalRef.value.onOpen(code)
	}
	const onPayFinish = () => {
		startCircleStatus()
	}

	/**
	 * 支付变更
	 */
	const payChangeModalRef = ref(null)
	const onPayChange = ({ id }) => {
		payChangeModalRef.value.onOpen(id)
	}
	const onPayChangeFinish = () => {
		startCircleStatus()
	}

	/**
	 * 合同删除
	 */
	const onDelete = ({ id }) => {
		Modal.confirm({
			title: '提示',
			icon: createVNode(ExclamationCircleOutlined),
			content: '确定要删除吗？',
			okText: '确认',
			cancelText: '取消',
			onOk: () => {
				contractApi.deleteContract({ id }).then(() => {
					table.value.refresh(true)
				})
			}
		})
	}

	/**
	 * 合同作废
	 */
	const onCancel = ({ id }) => {
		Modal.confirm({
			title: '提示',
			icon: createVNode(ExclamationCircleOutlined),
			content: '确定要作废吗？',
			okText: '确认',
			cancelText: '取消',
			onOk: () => {
				contractApi.cancelContract({ id }).then(() => {
					table.value.refresh(true)
				})
			}
		})
	}

	// 报单、派单
	const selectedRow = ref({})
	const bindVisibleScheduling = ref(false)
	const schedulingType = ref('1')
	const isTenantOderControls = ref(null)
	const toScheduling = (row, type) => {
		selectedRow.value = { ...row, list: row.serviceJson ? JSON.parse(row.serviceJson) : [] }
		bindVisibleScheduling.value = true
		schedulingType.value = type
	}
	const onOrderFinish = () => {
		table.value.refresh()
		bindVisibleScheduling.value = false
	}
</script>
<style lang="less" scoped>
	:deep(.ant-table-thead > tr > th::before) {
		width: 0 !important;
	}
	.center {
		text-align: center;
	}
	// :deep(.ant-table) {
	// 	min-height: calc(100vh - 350px);
	// }
</style>
